package com.itita.ww2.game.user;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.itita.ww2.core.WW2Exception;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * 奖励分发器
 * @author NorthLan
 *
 */
public class UserRewardDispatch {
	private static final Logger logger = LoggerFactory.getLogger(UserRewardDispatch.class);
	// private UserProfile userProfile;
	private Vector<IUserRewardListener> m_UserRewardListeners = new Vector<>();

	//	public UserRewardManager(UserProfile userProfile) {
	//		this.userProfile = userProfile;
	//	}

	public void addListener(IUserRewardListener listener) {
		m_UserRewardListeners.add(listener);
	}

	public ISFSObject onReward(RewardType type, ISFSObject params) {
		JsonObject ref = new JsonObject();
		for (Iterator<IUserRewardListener> iter = m_UserRewardListeners.iterator(); iter.hasNext();) {
			try {
				Map<String, Object> result = iter.next().onReward(type, params);
				if (result == null) {
					continue;
				}
				if (result.size() <= 0) {
					continue;
				}
				for (Entry<String, Object> entry : result.entrySet()) {
					ref.add(entry.getKey(), new GsonBuilder().create().toJsonTree(entry.getValue()));
				}
			} catch (Exception e) {
				if (e instanceof WW2Exception) {
					WW2Exception wwE = (WW2Exception) e;
					logger.error("OnReward Error: {} | {}", wwE.getExCode().getValue(), wwE.getMessage());
				} else {
					e.printStackTrace();
				}
				continue;
			}
		}
		return SFSObject.newFromJsonData(ref.toString());
	}

	public static enum RewardType {
		GM, // GM 赠送
		MISSION_COMPLETE, // 关卡完成 
		// MISSION_RUSH, // 掠夺关卡(扫荡) 转移到使用物品当中
		LOTTERY, // 抽奖
		CITY_SPECIAL_PRODUCT, // 城池特产
		PAYMENT, // 充值
		TIME_LIMIT_CARD, // 时限卡
	}

	public interface IUserRewardListener {
		public Map<String, Object> onReward(RewardType type, ISFSObject params) throws Exception;
	}
}
